package com.kclmedu.sst.servlet;

import com.kclmedu.sst.util.VerifyCodeBean;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/********************
 * 验证码Servlet
 *
 */
@WebServlet(value = "/checkcode")
public class CheckCodeServlet extends HttpServlet {

    private VerifyCodeBean verifyCodeBean = new VerifyCodeBean();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 通过 VerifyCodeBean 来生成验证码
        BufferedImage image = verifyCodeBean.getImage();
        //获取码证码上的字符，以便后绪进行验证
        String text = verifyCodeBean.getText();
        //把这个内容保存到 session 范围中
        req.getSession().setAttribute("CHECKCODE",text);
        System.out.println("--- > 验证码："+text);
        //把验证码的内容输出到客户端
        /** 设置浏览器不缓存图片*/
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");
        resp.setDateHeader("expires", -1);
        //获取输出流
        ServletOutputStream out = resp.getOutputStream();
        //写入到客户端
        verifyCodeBean.output(image,out);
    }
}
